package com.awan.model;

import java.util.ArrayList;
import java.util.List;

import com.awan.controller.Chat;
import com.awan.utils.Constanta;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ChatDatabaseHandler extends SQLiteOpenHelper {	
	
	private static String TAG;
	
	private static final String ID_FIELD = "id";
	private static final String FROM_FIELD = "froms";
	private static final String TO_FIELD = "tos";
	private static final String MSG_FIELD = "msg";
	private static final String DATE_FIELD = "dates";
	
	private static final String RECENT_FIELD = "fjid";
	private static final String OFF_MSG = "offline";
	
	/**
	 * constructor
	 * */
	public ChatDatabaseHandler(Context context) {
		super(context, Constanta.DATABASE_NAME, null, Constanta.DATABASE_VERSION);
		TAG = getClass().getSimpleName();
		// TODO Auto-generated constructor stub
	}	

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		Log.e(TAG,"db created");
		String createTable = "CREATE TABLE " + Constanta.chatLogTable + "("+
				ID_FIELD+" INTEGER PRIMARY KEY, "+
				FROM_FIELD+" TEXT, "+
				TO_FIELD+" TEXT, "+
				MSG_FIELD+" TEXT, "+
				DATE_FIELD+" TEXT)";
		db.execSQL(createTable);

		String createRecentTable = "CREATE TABLE " + Constanta.chatRecentTable + " ("+
				ID_FIELD+" INTEGER PRIMARY KEY, "+RECENT_FIELD+" TEXT)";
		db.execSQL(createRecentTable);
		
		
	}
	
	public void setRecentChat(String jid){
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(RECENT_FIELD, jid);
		db.insert(Constanta.chatRecentTable, null, values);
		db.close();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		Log.e(TAG,"db onUpgrade oldVersion ="+oldVersion+" newVersion ="+newVersion);
		db.execSQL("ALTER TABLE " + Constanta.chatLogTable + " ADD COLUMN " + OFF_MSG+" TEXT");
		//onCreate(db);
	}
	
	public List<Chat> getAllChat(String fJid) {
	    List<Chat> contactList = new ArrayList<Chat>();
	    
	    String selectQuery = "SELECT * FROM " + Constanta.chatLogTable + 
	    		" WHERE " + 
	    		FROM_FIELD + " like '%"+fJid+"%' or " + 
	    		TO_FIELD + " like '%"+fJid+"%'";
	 
	    SQLiteDatabase db = this.getReadableDatabase();
	    Cursor cursor = db.rawQuery(selectQuery, null);
	    if(cursor.getCount()>0){
	    	// looping through all rows and adding to list
		    if (cursor.moveToFirst()) {
		        do {
		        	Chat chat = new Chat();
		        	chat.setId(Integer.parseInt(cursor.getString(0)));
		        	chat.setFrom(cursor.getString(1));
		        	chat.setTo(cursor.getString(2));
		        	chat.setMsg(cursor.getString(3));
		        	chat.setDate(cursor.getString(4));
		            // Adding chat to list
		            contactList.add(chat);
		        } while (cursor.moveToNext());
		    }
	    }	    
	    cursor.close();
	    db.close();
	    return contactList;
	}
	
	public List<Chat> getOffChat(String fJid) {
	    List<Chat> contactList = new ArrayList<Chat>();
	    String off="offline";
	    String selectQuery = "SELECT * FROM " + Constanta.chatLogTable + 
	    		" WHERE offline='" + off;
	 
	    SQLiteDatabase db = this.getReadableDatabase();
	    Cursor cursor = db.rawQuery(selectQuery, null);
	    if(cursor.getCount()>0){
	    	// looping through all rows and adding to list
		    if (cursor.moveToFirst()) {
		        do {
		        	Chat chat = new Chat();
		        	chat.setId(Integer.parseInt(cursor.getString(0)));
		        	chat.setFrom(cursor.getString(1));
		        	chat.setTo(cursor.getString(2));
		        	chat.setMsg(cursor.getString(3));
		        	chat.setDate(cursor.getString(4));
		            // Adding chat to list
		            contactList.add(chat);
		        } while (cursor.moveToNext());
		    }
	    }	    
	    cursor.close();
	    db.close();
	    return contactList;
	}
	

	
	public void addChat(String from, String to, String msg, String date, String offMsg){
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(FROM_FIELD, from);
		values.put(TO_FIELD, to);
		values.put(MSG_FIELD, msg);
		values.put(DATE_FIELD, date);
		values.put(OFF_MSG, offMsg);
		db.insert(Constanta.chatLogTable, null, values);
		db.close();
		Log.e(TAG,"ol mesg "+msg);
		Log.e(TAG,"off mesg "+offMsg);
	}
	
	public List<Chat> getCurrentChat() {
		List<Chat> chatList = new ArrayList<Chat>();
		String selectQuery = "SELECT DISTINCT " + RECENT_FIELD + " FROM " + Constanta.chatRecentTable + 
	    		" WHERE " + 
	    		RECENT_FIELD + " <> 'Me'"/* or " + 
	    		TO_FIELD + " <> 'Me'"*/;
		 SQLiteDatabase db = this.getReadableDatabase();
		    Cursor cursor = db.rawQuery(selectQuery, null);
		    Constanta.currentChatCount = cursor.getCount();
		    if(cursor.getCount()>0){
		    	// looping through all rows and adding to list
			    if (cursor.moveToFirst()) {
			        do {
			        	Chat chat = new Chat();			        	
			        	chat.setFrom(cursor.getString(0));
			        	chatList.add(chat);
			        } while (cursor.moveToNext());
			    }
		    }	    
		    cursor.close();
		    db.close();
		return chatList;
	}
	
	public void deleteRecentChat(String fjid){		
		SQLiteDatabase db = this.getWritableDatabase();			
		String deleteRecentTable = "DELETE FROM " + Constanta.chatRecentTable + " WHERE "+RECENT_FIELD+" = '"+fjid+"'";
		db.execSQL(deleteRecentTable);		
		String deleteChatTable = "DELETE FROM " + Constanta.chatLogTable + " WHERE "+FROM_FIELD+" = '"+fjid+"' or "+TO_FIELD+" = '"+fjid+"'";
		db.execSQL(deleteChatTable);		
		db.close();
	}
	
	public void deleteAllRecentChat(){
		SQLiteDatabase db = this.getWritableDatabase();				
		String deleteRecentTable = "DELETE FROM " + Constanta.chatRecentTable;
		db.execSQL(deleteRecentTable);		
		String deleteChatTable = "DELETE FROM " + Constanta.chatLogTable;
		db.execSQL(deleteChatTable);		
		db.close();
	}	
}
